package com.transpeed.payservice.pay.unionpay;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;

import org.json.JSONObject;

import com.transpeed.payservice.Utils.JsonUtils;
import com.transpeed.payservice.Utils.UmsPayUtils;
import com.transpeed.payservice.log.Log;

public class GetUmsPayQRCode {
	public static final String ADD_URL = "http://umspay.izhong.me/netpay-route-server/api/";

	public static void test_trade_precreate() {
		try {
			// 创建连接
			URL url = new URL(ADD_URL);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			connection.connect();
			// POST请求
			DataOutputStream out = new DataOutputStream(connection.getOutputStream());
			
			String SystemNumber = "3075";//系统编号	
			String qrCodeId = UmsPayUtils.getQRCodeId(SystemNumber);//二维码ID
			String qrCodeUrl = UmsPayUtils.getQRCodeUrl(qrCodeId);
			String BillNo = UmsPayUtils.getBillNo(SystemNumber);

			HashMap<String, Object> UmsPayQRCode = new HashMap<String, Object>();
			UmsPayQRCode =UmsPayUtils.constructHashMap_getQRCode("123","1",BillNo, qrCodeId, SystemNumber);

			Log.Write("发送Json为 \n" + JsonUtils.formatAsJSON(new JSONObject(UmsPayQRCode).toString()),"UmsPay");
			
			byte [] bytes =  new JSONObject(UmsPayQRCode).toString().getBytes("UTF-8");
			out.write(bytes);
			out.flush();
			out.close();
			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "gbk");
				sb.append(lines);
			}

			reader.close();
			// 断开连接
			connection.disconnect();

			Log.Write("接收Json为 \n" + JsonUtils.formatAsJSON(sb.toString()),"UmsPay");

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
//		Log.Write(url + "&" + outTradeNo, "UmsPay");
//		return url + "&" + outTradeNo;

	}

	public static void main(String[] args) {
		test_trade_precreate();
	}
}
